// 模拟请求函数
function fetchFn (url) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('成功')
    }, 2000)
  })
}

// 创建请求池函数
function createRequestPool (poolSize) {
  const pool = []
  const temp = []

  return function (url) {
    function runTask () {
      while (temp.length < poolSize && pool.length) {
        const r = pool.shift()
        temp.push(r)
        fetchFn(r.url)
          .then((res) => {
            r.resolve(res)
          })
          .catch((err) => {
            r.reject(err)
          })
          .finally(() => {
            temp.splice(temp.indexOf(r), 1)
            runTask()
          })
      }
    }

    return new Promise((resolve, reject) => {
      pool.push({
        url,
        resolve,
        reject,
      })

      runTask()
    })
  }
}

// 测试验证
const request = createRequestPool(3)

request('1').then((res) => {
  console.log(1)
})
request('2').then((res) => {
  console.log(2)
})
request('3').then((res) => {
  console.log(3)
})
request('4').then((res) => {
  console.log(4)
})
request('5').then((res) => {
  console.log(5)
})
request('6').then((res) => {
  console.log(6)
})
request('7').then((res) => {
  console.log(7)
})
request('8').then((res) => {
  console.log(8)
})
request('9').then((res) => {
  console.log(9)
})
request('10').then((res) => {
  console.log(10)
})